package codeRandomThoughts.Test46全排列;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        boolean[] visited = new boolean[nums.length];
        List<Integer> path = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        backTrack(nums, visited, path, result);
        return result;
    }

    //回溯算法不用返回值
    void backTrack(int[] nums, boolean[] visited, List<Integer> path, List<List<Integer>> result) {
        //结束递归
        if (path.size() == nums.length) {
            //必须new一个,不能一直用相同的path
            result.add(new ArrayList<>(path));
            return;
        }

        //这里面的for循环不用startIndex,因为每次都要遍历全部元素
        for (int i = 0; i < nums.length; i++) {
            if (!visited[i]) {
                path.add(nums[i]);
                visited[i] = true;//要始终记录访问过的节点
                backTrack(nums, visited, path, result);
                visited[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }
}
